package cn.lic.tool.poi.excel.function;

import java.math.BigDecimal;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ContextWarp {
	private JSONObject json;
	ContextWarp (JSONObject ctx) {
		this.json = ctx;
	}
	
	public Object get(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return null;
		}
		return ctx.get(keys[keys.length - 1]);
	}

	public int getInteger(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return 0;
		}
		return ctx.getInteger(keys[keys.length - 1]);
	}
	
	public float getFloat(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return 0f;
		}
		return ctx.getFloat(keys[keys.length - 1]);
	}
	
	public String getString(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return null;
		}
		return ctx.getString(keys[keys.length - 1]);
	}
	
	public boolean getBoolean(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return false;
		}
		return ctx.getBoolean(keys[keys.length - 1]);
	}
	
	public BigDecimal getBigDecimal(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return null;
		}
		return ctx.getBigDecimal(keys[keys.length - 1]);
	}
	
	public JSONObject getJSONObject(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return null;
		}
		return ctx.getJSONObject(keys[keys.length - 1]);
	}
	
	public JSONArray getJSONArray(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return null;
		}
		return ctx.getJSONArray(keys[keys.length - 1]);
	}
	
	public boolean containsKey(String key) {
		String[] keys = toKeys(key);
		JSONObject ctx = getNamespaceCtx(keys);
		if (ctx == null) {
			return false;
		}
		return ctx.containsKey(keys[keys.length - 1]);
	}
	
	private JSONObject getNamespaceCtx(String[] keys) {
		JSONObject ctx = json;
		int length = keys.length - 1;
		for (int i = 0; i < length; i++) {
			ctx = ctx.getJSONObject(keys[i]);
			if (ctx == null) {
				return null;
			}
		}
		return ctx;
	}
	private static String[] toKeys(String key) {
		if (key == null) {
			return null;
		}
		return key.split("\\.");
	}
}
